import { Button, Card, Checkbox, Form, Input, message } from 'antd'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { userLogin } from '../../store/action/login.js'
import { isAuth } from '../../utils/token.js'
// 导入样式
import './index.scss'
function Login() {
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = (values: any) => {
    if (values.username === 13911111111 && values.password === '246810') {
      dispatch(userLogin(values) as any)
      history.push('/home')
      message.success('登录成功!')
    } else {
      message.error('请输入正确的账号或密码!')
    }
  }

  const onFinishFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo)
  }

  const validAgree = (rule: object, value: boolean) => {
    return value
      ? Promise.resolve()
      : Promise.reject(new Error('请同意用户协议'))
  }

  // 如果已经登录则跳到首页
  useEffect(() => {
    if (isAuth()) {
      history.push('/home')
    }
  }, [])
  return (
    <div className="login">
      <Card className="Card">
        <h1 className="title">记账小能手</h1>
        <Form
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          // 初始化表单数据的默认值d
          initialValues={
            // 属性名和Form.Item的name属性对应
            { username: 13911111111, password: '246810', agree: true }
          }>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入账号!' }]}>
            <Input />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}>
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[{ validator: validAgree }]}>
            <Checkbox className="login-checkbox-label">
              我已阅读并同意[用户协议]和[隐私条款]
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button block size="large" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
